#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTime>


struct _board_mac AL_Board_Mac;

#define RED_DEF  "background-color:rgb(255,0,0)"
#define GREED_DEF  "background-color:rgb(0,255,0)"
#define BLUE_DEF  "background-color:rgb(0,0,255)"

//  QString 等长分割
QStringList splitFormatString(const QString& org, int nSpacing = 1)
{
    QStringList list;
      QString result = org;
      if (org.size() <= nSpacing) {
          result.push_front(org);
      } else {
          result.clear();
          for (int i=0; i<org.size(); ) {
            result=org.mid(i, nSpacing);
            list.append(result);
            i += nSpacing;
            if (i < org.size()) {
                // list.append(result);
                ;
            }
          }
      }
      return list;

}


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    isConn_heart=0;

    // ui->readymac0->setEnabled(false);
     ui->readymac1->setEnabled(false);
    // ui->recv_mac0->setEnabled(false);
     ui->recv_mac1->setEnabled(false);
    // ui->socket_conn_status->setEnabled(false);
    // ui->mac_status_0->setEnabled(false);
     ui->mac_status_1->setEnabled(false);
    // ui->mac_status_0->setStyleSheet("color:red");
    // ui->mac_status_1->setStyleSheet("color:red");
     ui->label_4->setEnabled(false);
     ui->label_6->setEnabled(false);


    printf("1\n");
    ui->recv_mac0->setReadOnly(true);
    //ui->recv_mac1->setReadOnly(true);
    ui->readymac0->setReadOnly(true);
   // ui->readymac1->setReadOnly(true);

    QString show_str=" 等待MYC网络连接... ";
    ui->socket_conn_status->setStyleSheet(BLUE_DEF);
    ui->socket_conn_status->setText(show_str); 
    ui->logs_eth->setStyleSheet(BLUE_DEF);
    ui->logs_eth->setText(show_str); 

    ui->mac_status_0->setText("空");
    //ui->mac_status_1->setText("空");

    ui->maccsvopen->setText("加载MAC数据库文件");
    ui->maccsvopen->setStyleSheet(BLUE_DEF);
    ui->maccsvsaveas->setText("导出MAC数据库文件");
    ui->maccsvsaveas->setStyleSheet(BLUE_DEF);

    connect(ui->maccsvopen, SIGNAL(clicked()), this, SLOT(copy_csvfile()));
    connect(ui->maccsvsaveas, SIGNAL(clicked()), this, SLOT(save_csvfile()));
    

    // lineedit text 居中显示
    ui->recv_mac0->setAlignment(Qt::AlignCenter);
    //ui->recv_mac1->setAlignment(Qt::AlignCenter);
    ui->readymac0->setAlignment(Qt::AlignCenter);
    //ui->readymac1->setAlignment(Qt::AlignCenter);
    ui->lineEdit_3->setAlignment(Qt::AlignCenter);

    /*读取mac的数据库*/
    load_csvfile();

    ui->lineEdit_2->setFocus();//设置焦点
   
       /*timer set*/
       timer_scan= new QTimer(this);
       connect(timer_scan,SIGNAL(timeout()),this,SLOT(scan_check()));

       timer_updateui= new QTimer(this);
       connect(timer_updateui,SIGNAL(timeout()),this,SLOT(update_socketstatus()));

        timer_scan->start(500);
        timer_updateui->start(2000);

       m_server = new QTcpServer();
       m_server->listen(QHostAddress::Any,8000);
       connect(m_server,SIGNAL(newConnection()),this,SLOT(server_new_connect()));

    //    ui->pushButton_2->setStyleSheet("background-color:rgb(255,0,0)");  // 红色
    //    ui->pushButton_3->setStyleSheet("background-color:rgb(0,255,0)");  // 绿色

        // init status
       ui->mac_status_0->setStyleSheet(RED_DEF);  // 红色
       //ui->mac_status_1->setStyleSheet(RED_DEF);  //
       printf("5\n");
}

MainWindow::~MainWindow()
{
    m_server->close();
    m_server->deleteLater();
    delete ui;
}

int MainWindow::copy_csvfile()
{
    QString fileName_new=CSVFILE_PATH;

    QString fileName = QFileDialog::getOpenFileName(this, tr("打开数据库文件"), "/run/media",tr("Image Files (*.csv)"));
    qDebug()<< "file ===== " << fileName << endl;

     if(fileName.length()>0){
     
        QFile::remove(fileName_new);
        // targetDir.remove(fileInfo.fileName()); 
        if(QFile::copy(fileName,fileName_new)){
            qDebug()<<QStringLiteral("copy ok");
            m_mac_csvfile.csv_closefile();
            load_csvfile();
            return 0;
        }else{
            QString show_str=" MAC数据库加载失败，请重新加载... ";
            ui->socket_conn_status->setStyleSheet(RED_DEF);
        }
     }else{
        QString show_str=" MAC数据库加载取消，请重新加载... ";
        ui->socket_conn_status->setStyleSheet(RED_DEF);
        ui->socket_conn_status->setText(show_str); 
     }
}

int MainWindow::load_csvfile()
{
    QString show_str;
    if(!m_mac_csvfile.csv_openfile(CSVFILE_PATH)){
        // qDebug()<< "start read mac data form csv" << endl;
        m_mac_csvfile.csv_readall();
        if(m_mac_csvfile.list_mac_var.length()>0){
            show_str=" MAC数据库加载成功... ";
            ui->socket_conn_status->setStyleSheet(GREED_DEF);
            ui->socket_conn_status->setText(show_str); 
             return 0;
        }else{
            show_str=" MAC数据库加载失败，请重新加载... ";
            ui->socket_conn_status->setStyleSheet(RED_DEF);
            ui->socket_conn_status->setText(show_str); 
            return -1;
        }
           
    }else{
        show_str=" MAC数据库没有找到，请重新加载... ";
        ui->socket_conn_status->setStyleSheet(RED_DEF);
        ui->socket_conn_status->setText(show_str); 
        return -1;
    }
}

int MainWindow::save_csvfile()
{
    QString show_str;
    QString filename = QFileDialog::getSaveFileName(this, tr("选择保存文件路径"), "/run/media/myirmacback.csv", tr("csv (*.csv)"));

    // qDebug()<< "sava csv path" << filename <<endl;
    QFile::remove(filename);
    if(QFile::copy(CSVFILE_PATH,filename)){
        qDebug()<<QStringLiteral("back ok");
        show_str=" MAC数据库导出成功 ";
        ui->socket_conn_status->setStyleSheet(GREED_DEF);
        ui->socket_conn_status->setText(show_str); 
        return 0;
    }else{
        show_str=" MAC数据库导出失败 ";
        ui->socket_conn_status->setStyleSheet(RED_DEF);
        ui->socket_conn_status->setText(show_str);
        return -1;
    }
    
}

int  kk=0;

int MainWindow::update_socketstatus()
{
    unsigned int  heart=0xCC;
      int ret =-1;
    if(kk==0){
        isConn_heart=0;
    }
    kk++;
        // // int ret = m_socket->write("wake hands");
    //error
    if(isConn_socket)
        ret= m_socket->write((char*)&heart,sizeof(AL_Board_Mac.MacData_sd.cmd));

    if(kk>=2){
        // qDebug()<< "socket thread = "<< isConn_heart  << endl;
        kk=0;

        if(isConn_heart==0){

            QString show_str="网络连接断开";
            ui->logs_eth->setText(show_str); 
            ui->logs_eth->setStyleSheet(RED_DEF);
            // clear all status 
            // ui->socket_conn_status->setStyleSheet(RED_DEF);
            ui->mac_status_0->setStyleSheet(RED_DEF);  
            //ui->mac_status_1->setStyleSheet(RED_DEF);
            ui->readymac0->setText("");
            //ui->readymac1->setText("");

            // ui->recv_mac0->setText("");
            // ui->recv_mac1->setText("");
            // show_str="............................";
            // ui->socket_conn_status->setStyleSheet(RED_DEF);
            // ui->socket_conn_status->setText(show_str); 

        }else if(isConn_heart==1){
            QString show_str;
            // show_str="网络连接正常，请扫描条形码获取MAC ... ";
            // qDebug()<< "server_new_connect" << endl;

            // ui->socket_conn_status->setStyleSheet(GREED_DEF);
            // ui->socket_conn_status->setText(show_str); 

            show_str="网络连接正常";
            ui->logs_eth->setStyleSheet(GREED_DEF);
            ui->logs_eth->setText(show_str); 
        }
    }
    return 0;
}

int MainWindow::server_new_connect()
{
    QString show_str;
    show_str="网络连接正常，请扫描条形码获取MAC ... ";
    qDebug()<< "server_new_connect" << endl;

    ui->socket_conn_status->setStyleSheet(GREED_DEF);
    ui->socket_conn_status->setText(show_str); 

    show_str="网络连接正常";
    ui->logs_eth->setStyleSheet(GREED_DEF);
    ui->logs_eth->setText(show_str); 

    isConn_socket=1;

    // client conn
    m_socket =  m_server->nextPendingConnection();
    connect(m_socket,SIGNAL(readyRead()),this,SLOT(socket_read_data()));
    connect(m_socket,SIGNAL(disconnected()),this,SLOT(socket_disconnect()));

    return 0;
}

void MainWindow::update_recvmac()
{
    // update ui and csv
    QString tmp,str_mac0;

    for(int i=0;i<6;i++){
        tmp = QString::number(AL_Board_Mac.MacData_rv.MacaValue_a[i],16).toUpper();
        str_mac0.append(tmp);
        // csv_amc.append(tmp);
        if(i!=5) str_mac0.append(":");
    }
    ui->recv_mac0->setText(str_mac0);

    str_mac0.clear();
    for(int i=0;i<6;i++){
        tmp = QString::number(AL_Board_Mac.MacData_rv.MacaValue_b[i],16).toUpper();
        str_mac0.append(tmp);
        // csv_amc.append(tmp);
        if(i!=5) str_mac0.append(":");
    }
    ui->recv_mac1->setText(str_mac0);
}
void MainWindow::update_ui_mac()
{
    // update ui and csv
    QString tmp,str_mac0;
    QString csv_amc;
    QString  insert_str,lines;
    int indexline=0;
    for(int i=0;i<6;i++){
        //tmp = QString::number(AL_Board_Mac.MacData_rv.MacaValue_a[i],16,2).toUpper();
	tmp = QString("%1").arg(AL_Board_Mac.MacData_rv.MacaValue_a[i], 2, 16, QLatin1Char('0')).toUpper()   ; 
	//qDebug()<< " read line mac i000c00000  === " << tmp << endl;
        str_mac0.append(tmp);
        csv_amc.append(tmp);
        if(i!=5) str_mac0.append(":");
    }
    //
     qDebug()<< " recv one mac === " << str_mac0 << endl;
    indexline=m_mac_csvfile.list_find_mac(csv_amc);
    if(indexline>=0){
        indexline +=1;
        lines=QString("%1").arg(indexline, 5, 10, QChar('0'));
        insert_str.append(lines);
        insert_str.append(',');
        insert_str.append(csv_amc);
        insert_str.append(',');
        insert_str.append('1');
        qDebug()<<QStringLiteral("ALEX CSV LINES 1= ")<< indexline;
        qDebug()<<QStringLiteral("ALEX CSV LINES 2= ")<< insert_str;
        m_mac_csvfile.csv_update_line(indexline,insert_str);
        m_mac_csvfile.csv_readall();
    }
    ui->recv_mac0->setText(str_mac0);

    str_mac0.clear();
    csv_amc.clear();
    insert_str.clear();
    lines.clear();
    for(int i=0;i<6;i++){
        tmp = QString::number(AL_Board_Mac.MacData_rv.MacaValue_b[i],16).toUpper();
        str_mac0.append(tmp);
        csv_amc.append(tmp);
        if(i!=5) str_mac0.append(":");
    }
    indexline=m_mac_csvfile.list_find_mac(csv_amc);
    if(indexline>=0){
        indexline +=1;
        lines=QString("%1").arg(indexline, 5, 10, QChar('0'));
        insert_str.append(lines);
        insert_str.append(',');
        insert_str.append(csv_amc);
         insert_str.append(',');
        insert_str.append('1');

        m_mac_csvfile.csv_update_line(indexline,insert_str);
        m_mac_csvfile.csv_readall();
        // m_mac_csvfile.list_mac_line[0]
    }
    ui->recv_mac1->setText(str_mac0);

}

void MainWindow::socket_read_data()
{
    int len = m_socket->read((char*)&AL_Board_Mac.MacData_rv.cmd,1024);
    if(len>0){
        AL_Board_Mac.MacData_sd.cmd=0x09;
        // m_socket->write((char*)&AL_Board_Mac.MacData_sd.cmd,20);
        if(AL_Board_Mac.MacData_rv.cmd==0x0A){
            AL_Board_Mac.MacData_sd.cmd=0x1A;
            // std::cout << " send mac" << std::endl;
            //从扫描枪读取MAC
            // AL_Board_Mac.MacData_sd.MacaValue_a[0]=0x01;
            // AL_Board_Mac.MacData_sd.MacaValue_a[1]=0x11;
            // AL_Board_Mac.MacData_sd.MacaValue_a[2]=0x21;
            // AL_Board_Mac.MacData_sd.MacaValue_a[3]=0x31;
            // AL_Board_Mac.MacData_sd.MacaValue_a[4]=0x41;
            // AL_Board_Mac.MacData_sd.MacaValue_a[5]=0x51;
            // sleep(5);
            //send(*tmp, &AL_Board_Mac.MacData_sd.cmd, sizeof(_test_mac), 0);
        }

        // 板子已经有MAC
        // 接收反馈的信息
        else if(AL_Board_Mac.MacData_rv.cmd==0x0B){

             qDebug()<< " recv one client 0x0B" << endl;
            // std::cout << "  recv mac statu =" << hex <<AL_Board_Mac.MacData_rv.statu <<std::endl;

            // update ui
            // update_ui_mac();
            update_recvmac();
        }
        // 获取MAC写入情况
        else if(AL_Board_Mac.MacData_rv.cmd==0x1B){

            qDebug()<< " recv one client 0x1B" << endl;
            // update ui  and sql
            update_ui_mac();
            
            //  update MAC status  ---> ui
            switch (AL_Board_Mac.MacData_rv.status)
            {
            case 0x0:
                ui->mac_status_0->setStyleSheet(RED_DEF);
                //ui->mac_status_1->setStyleSheet(RED_DEF);
                ui->mac_status_0->setText("MAC0 写入MYC失败");
                //ui->mac_status_1->setText("MAC1 写入MYC失败");
                break;
            case 0x1:
                ui->mac_status_0->setStyleSheet(GREED_DEF);
                //ui->mac_status_1->setStyleSheet(RED_DEF);

                ui->mac_status_0->setText("MAC0 写入MYC完成 ");
                //ui->mac_status_1->setText("MAC1 写入MYC失败,请检查");
                break;
            case 0x2:
                ui->mac_status_0->setStyleSheet(RED_DEF);
                //ui->mac_status_1->setStyleSheet(GREED_DEF);

                ui->mac_status_0->setText("MAC0 写入MYC失败,请检查");
                //ui->mac_status_1->setText("MAC1 写入MYC完成");
                break;
            case 0x3:
                ui->mac_status_0->setStyleSheet(GREED_DEF);
                //ui->mac_status_1->setStyleSheet(GREED_DEF);

                ui->mac_status_0->setText("MAC0 写入MYC完成");
                //ui->mac_status_1->setText("MAC1 写入MYC完成");
                break;
            
            default:
                break;
            }
       }else if(AL_Board_Mac.MacData_rv.cmd==0xCC){
            isConn_heart=1;
       }

    }

}
// void MainWindow::ffff()
// {

// }
void MainWindow::socket_disconnect()
{
    qDebug()<< "one client disconnect" << endl;
    isConn_socket=0;

    QString show_str="网络连接断开";
    ui->logs_eth->setText(show_str); 
    ui->logs_eth->setStyleSheet(RED_DEF);

    // clear all status 
    ui->socket_conn_status->setStyleSheet(RED_DEF);

    ui->mac_status_0->setStyleSheet(RED_DEF);  
   // ui->mac_status_1->setStyleSheet(RED_DEF);
    
    ui->readymac0->setText("");
    //ui->readymac1->setText("");

    ui->recv_mac0->setText("");
    //ui->recv_mac1->setText("");
}

// 条形码的MAC 长度
#define MAC_LEN_1   12   // 一个MAC = 000C29369720
#define MAC_LEN_17  17   // one MAC =00:0C:29:36:97:20 or 00-0C-29-36-97-20

#define MAC_LEN_2   24   // 两个MAC

int MainWindow::scan_check()
{
    QString show_str;
    ui->lineEdit_2->setFocus();//设置焦点
    QString  tmp_mac=ui->lineEdit_2->text();
    int len=tmp_mac.length();
    if(tmp_mac.length())
         ui->lineEdit_3->setText(tmp_mac);
    
    if((len==MAC_LEN_1) || (len == MAC_LEN_17) )
    {
        show_str="扫码成功";
        ui->socket_conn_status->setStyleSheet(GREED_DEF);
        ui->socket_conn_status->setText(show_str); 

        qDebug()<< "scan mac data = " << tmp_mac << endl;
        // show_str="网络连接正常";
        // ui->logs_eth->setText(show_str); 
        // ui->logs_eth->setStyleSheet(GREED_DEF);
        //MAC_LEN_17去除格式“-” or “：”
        if(len == MAC_LEN_17)
        {
            char array[]={'-', ':'};
            int length = sizeof (array)/sizeof (char);
            for(int i=0; i < length; i++)
            {
                   QString tmp = QString(array[i]);
                   if(tmp_mac.contains(tmp))
                   {
                       tmp_mac = tmp_mac.replace(tmp,"");
                   }
            }
        }

        QStringList list_mac_tmp=splitFormatString(tmp_mac,2);
        QString str_tmp;
        for(int i=0; i< 6; i++){
            if(i<list_mac_tmp.size()){
                str_tmp.append(list_mac_tmp[i]);
                if(i!=5)
                    str_tmp.append(":");
             }
         }
         ui->readymac0->setText(str_tmp);

        // scan_mac = tmp_mac;

        // 清空
        ui->lineEdit_2->setText("");
        

        //检查mac的合法性

        //检查mac是否存在数据库中且mac在数据库中是否已经使用
        int  indexline=m_mac_csvfile.list_find_mac(tmp_mac);

        if(indexline>=0){
      
            if(m_mac_csvfile.list_mac_status[indexline].compare("1") ==0 )
            {
                printf("count = %d\n",m_mac_csvfile.list_mac_line[indexline].count());
                show_str="扫码成功,MAC已经被使用,请重新扫码";
                ui->socket_conn_status->setStyleSheet(RED_DEF);
                ui->socket_conn_status->setText(show_str); 

                ui->mac_status_0->setStyleSheet(RED_DEF);
                //ui->mac_status_1->setStyleSheet(RED_DEF);

                ui->mac_status_0->setText("MAC0 写入MYC失败,请检查");
                //ui->mac_status_1->setText("MAC1 写入MYC失败,请检查");

                return -1;
            }
        }else{
            show_str="数据库中不存在此MAC,请重新扫码";
            ui->socket_conn_status->setStyleSheet(RED_DEF);
            ui->socket_conn_status->setText(show_str); 
            return -1;
        }

        // 设置数据
        AL_Board_Mac.MacData_sd.cmd=0x1A;
        AL_Board_Mac.MacData_sd.MacNum=1;

        // QString to int 

        // QString readymac= ui->readymac0->text();
        // QStringList list_macvalue=splitFormatString(readymac,2);

        // QString readymac2= ui->readymac1->text();
        // QStringList list_macvalue2=splitFormatString(readymac2,2);
        bool ok;
        for(int i=0; i< 6; i++){

            if(i<list_mac_tmp.size())
                AL_Board_Mac.MacData_sd.MacaValue_a[i] = list_mac_tmp[i].toInt(&ok,16);
            if(i<list_mac_tmp.size())
                AL_Board_Mac.MacData_sd.MacaValue_b[i] = list_mac_tmp[i].toInt(&ok,16);
        }
        // send data 
        if(isConn_socket)
            m_socket->write((char*)&AL_Board_Mac.MacData_sd.cmd,sizeof(AL_Board_Mac));
    }
    else if(len==MAC_LEN_2){
        // 判断读取到两个MAC,相同则也是错误的

    }
    else
    {   
        if(len>0){
            qDebug()<< "scan data len = " << len << endl;
            // int textWidth = button->fontMetrics().width(m_text);
            QString  tmpStr = ui->socket_conn_status->fontMetrics().elidedText(m_text, Qt::ElideRight, contentsRect().width(), Qt::TextShowMnemonic);
            // int buttonWidth = contantsRect().width();
            // QString show_str="网络连接正常，扫码失败，请重新扫码 ... ";
            tmpStr =  "条形码不符合要求,请重新扫码...";
            ui->socket_conn_status->setStyleSheet(BLUE_DEF);
            ui->socket_conn_status->setText(tmpStr); 
        }
        // 清空
        ui->lineEdit_2->setText("");
        return -1;
    }

    return 0;
}

